"use client";
import React, { useEffect, useState } from "react";
import { Mail, Lock, User } from 'lucide-react';
import { showToast } from "@/components/ui/toast";
import { fetchApi } from "@/request/request";
import { useRouter } from '@/utils/router';

export default function Login() {
    const router = useRouter()
    const [isLogin, setIsLogin] = useState(true);
    const onLoginClick = () => {
        setIsLogin(!isLogin)
    }
    //登录
    const handleLogin = async (email: string, password: string) => {
        try {
            const res = await fetchApi("/api/user", {
                action: "login",
                params: {
                    email,
                    password,
                }
            }) as any
            // console.log(res)
            if (res.message == "success") {
                const { id, token, refreshToken, avatar, username, bookshelf } = res.data

                const user = { avatar, username, id }
                showToast('登陆成功')
                localStorage.setItem('token', token);
                localStorage.setItem("bookshelf", JSON.stringify(bookshelf))
                localStorage.setItem("user", JSON.stringify(user))
                localStorage.setItem('refreshToken', refreshToken);
                router.push("/")
            } else {
                showToast('检查账号密码')
            }
        } catch (error) {
            showToast('登陆失败')
        }
    };
    //注册
    const handleRegister = async (
        name: string,
        email: string,
        password: string
    ) => {
        try {
            const res = await fetchApi("/api/user",
                { action: "register", params: { name, email, password } }) as any
            // console.log(res)
            if (res.message == "success") {
                showToast("注册成功")
                setIsLogin(true);
            } else {
                showToast("注册失败，改邮箱已被使用")
            }
        } catch (error) {
            // console.log(error, "error");
            showToast("注册失败")
        }
    };
    return (
        <>
            <div className="bg-[#efefef] flex flex-col items-center justify-center 
            min-h-screen mx-auto  
            sm:max-w-sm md:max-w-md lg:max-w-lg">
                <div className="bg-[#ffffff] p-5 rounded-lg w-full">
                    {isLogin ? <LoginForm onSubmit={handleLogin} onRegisterClick={onLoginClick} />
                        : <Register onSubmit={handleRegister} onLoginClick={onLoginClick} />}
                </div>
            </div>
        </>
    )
}


function Register({ onSubmit, onLoginClick }: {
    onSubmit: (name: string, email: string, password: string) => void,
    onLoginClick: () => void
}) {

    const [name, setName] = useState('');
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        if (password === confirmPassword) {
            onSubmit(name, email, password);
        }
    };
    return (
        <>
            <div className="w-full">
                <form onSubmit={handleSubmit} className="space-y-6">
                    <div>
                        <label htmlFor="name" className="block text-sm font-medium text-gray-700">
                            用户名
                        </label>
                        <div className="mt-1 relative">
                            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <User className="h-5 w-5 text-gray-400" />
                            </div>
                            <input
                                id="name"
                                type="text"
                                required
                                className="appearance-none block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-[#1f1f1f] focus:border-[#1f1f1f]"
                                value={name}
                                onChange={(e) => setName(e.target.value)}
                            />
                        </div>
                    </div>

                    <div>
                        <label htmlFor="email" className="block text-sm font-medium text-gray-700">
                            邮箱
                        </label>
                        <div className="mt-1 relative">
                            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <Mail className="h-5 w-5 text-gray-400" />
                            </div>
                            <input
                                id="email"
                                type="email"
                                required
                                className="appearance-none block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-[#1f1f1f] focus:border-[#1f1f1f]"
                                value={email}
                                onChange={(e) => setEmail(e.target.value)}
                            />
                        </div>
                    </div>

                    <div>
                        <label htmlFor="password" className="block text-sm font-medium text-gray-700">
                            密码
                        </label>
                        <div className="mt-1 relative">
                            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <Lock className="h-5 w-5 text-gray-400" />
                            </div>
                            <input
                                id="password"
                                type="password"
                                required
                                className="appearance-none block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-[#1f1f1f] focus:border-[#1f1f1f]"
                                value={password}
                                onChange={(e) => setPassword(e.target.value)}
                            />
                        </div>
                    </div>
                    {password !== confirmPassword && confirmPassword && (
                        <div className="text-sm text-red-500 mt-1">
                            两次输入的密码不一致，请重新输入
                        </div>
                    )}

                    <div>
                        <label htmlFor="confirmPassword" className="block text-sm font-medium text-gray-700">
                            确认密码
                        </label>
                        <div className="mt-1 relative">
                            <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                                <Lock className="h-5 w-5 text-gray-400" />
                            </div>
                            <input
                                id="confirmPassword"
                                type="password"
                                required
                                className="appearance-none block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-[#1f1f1f] focus:border-[#1f1f1f]"
                                value={confirmPassword}
                                onChange={(e) => setConfirmPassword(e.target.value)}
                            />
                        </div>
                    </div>

                    <div>
                        <button
                            type="submit"
                            className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                            disabled={!name || !email || !password || !confirmPassword}
                            onClick={handleSubmit}
                        >
                            注册
                        </button>
                    </div>

                    <div className="text-sm text-center">
                        <button
                            type="button"
                            onClick={onLoginClick}
                            className="font-medium text-indigo-600 hover:text-indigo-500"
                        >
                            已有账号
                        </button>
                    </div>
                </form>
            </div>
        </>)
}

function LoginForm({ onSubmit, onRegisterClick }: {
    onSubmit: (email: string, password: string) => void,
    onRegisterClick: () => void
}) {
    const [email, setEmail] = useState('');
    const [password, setPassword] = useState('');

    const handleSubmit = (e: React.FormEvent) => {
        e.preventDefault();
        onSubmit(email, password);
    };

    return (
        <div className="w-full">
            <form onSubmit={handleSubmit} className="space-y-6">
                <div>
                    <label htmlFor="email" className="block text-sm font-medium text-gray-700">
                        邮箱
                    </label>
                    <div className="mt-1 relative">
                        <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <Mail className="h-5 w-5 text-gray-400" />
                        </div>
                        <input
                            id="email"
                            type="email"
                            required
                            className="appearance-none block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                            value={email}
                            onChange={(e) => setEmail(e.target.value)}
                        />
                    </div>
                </div>

                <div>
                    <label htmlFor="password" className="block text-sm font-medium text-gray-700">
                        密码
                    </label>
                    <div className="mt-1 relative">
                        <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <Lock className="h-5 w-5 text-gray-400" />
                        </div>
                        <input
                            id="password"
                            type="password"
                            required
                            className="appearance-none block w-full pl-10 pr-3 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
                            value={password}
                            onChange={(e) => setPassword(e.target.value)}
                        />
                    </div>
                </div>

                <div>
                    <button
                        type="submit"
                        className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-indigo-600 hover:bg-indigo-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500"
                    >
                        登录
                    </button>
                </div>
                <div className="text-sm text-center">
                    <button
                        type="button"
                        onClick={onRegisterClick}
                        className="font-medium text-indigo-600 hover:text-indigo-500"
                    >
                        没有账号
                    </button>
                </div>
            </form>
        </div>
    );
}